import axios from 'axios'

axios.defaults.baseURL = 'http://localhost:8888/api/private/v1'

// 添加axios拦截器,为每一个请求都添加一个一个token:
axios.interceptors.request.use(function (config) {
  // 先从本地获取到token:
  let mytoken = localStorage.getItem('mytoken')
  // 如果token存在,则把他放进去:
  if (mytoken) {
    config.headers.Authorization = mytoken
  }
  // 请求需要发送回去
  return config
}, function (error) {
  return Promise.reject(error)
}
)

export const login = obj => axios.post('/login', obj).then(res => res.data)

export const getUserList = obj => axios.get('/users', { params: obj }).then(res => res.data)

// 添加用户
export const addUser = obj => axios.post('/users', obj).then(res => res.data)

// 删除用户:
export const deleteUser = id => axios.delete(`/users/${id}`).then(res => res.data)

// 修改用户状态
export const changeState = (id, type) => axios.put(`users/${id}/state/${type}`).then(res => res.data)

// 编辑用户信息
export const editUser = (id, obj) => axios.put(`/users/${id}`, obj).then(res => res.data)

// 分配用户角色
export const grantUserRole = (id, rid) => axios.put(`users/${id}/role`, { rid: rid }).then(res => res.data)

// 获取角色列表
export const getRoles = () => axios.get('/roles').then(res => res.data)

// 获取权限列表
export const getRightList = type => axios.get(`rights/${type}`).then(res => res.data)

// 删除角色指定权限
export const deleteRoleRight = (roleId, rightId) => axios.delete(`roles/${roleId}/rights/${rightId}`).then(res => res.data)

// 添加角色:
export const addRoler = obj => axios.post('/roles', obj).then(res => res.data)

// 删除角色:
export const deleteRoler = (id, obj) => axios.delete(`roles/${id}`, obj).then(res => res.data)

// 编辑角色:
export const editRoler = (id, obj) => axios.put(`roles/${id}`, obj).then(res => res.data)

// 授权角色
export const grantRole = (roleId, idsStr) => axios.post(`roles/${roleId}/rights`, { rids: idsStr }).then(res => res.data)

// 获取菜单权限
export const getMenus = () => axios.get('/menus').then(res => res.data)

// 商品分类数据
export const getCate = (type, pagesize, pagenum) => axios.get('/categories', { params: { type: type, pagesize: pagesize, pagenum: pagenum } }).then(res => res.data)

// 添加商品分类
export const addCate = obj => axios.post('/categories', obj).then(res => res.data)

// 删除商品分类:
export const deleteCate = id => axios.delete(`/categories/${id}`).then(res => res.data)

// 编辑商品分类:
export const editCate = (id, catName) => axios.put(`/categories/${id}`, catName).then(res => res.data)
